package com.example.smartall.ui;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.smartall.R;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.diaglog.LoadedDialog;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.utils.Constant;
import com.example.smartall.utils.SPUtils;
import com.example.smartall.utils.TextUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;

/**
 * @Author: abbas
 * @CreateDate: 2022/2/12
 * @Description: 注册
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private ImageView imBack;
    private TextView tvTitle;
    private ImageView avater;
    private EditText etAvater;
    private EditText etName;
    private EditText etNick;
    private EditText etPwd;
    private EditText etPhone;
    private RadioButton rbNan;
    private RadioButton rbNv;
    private EditText etEmail;
    private EditText etIdCard;
    private Button btRegister;


    private String img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        init();
        initEvent();
    }

    @Override
    public void init() {
        imBack = (ImageView) findViewById(R.id.im_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        avater = (ImageView) findViewById(R.id.avater);
        etAvater = (EditText) findViewById(R.id.et_avater);
        etName = (EditText) findViewById(R.id.et_name);
        etNick = (EditText) findViewById(R.id.et_nick);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        etPhone = (EditText) findViewById(R.id.et_phone);
        rbNan = (RadioButton) findViewById(R.id.rb_nan);
        rbNv = (RadioButton) findViewById(R.id.rb_nv);
        etEmail = (EditText) findViewById(R.id.et_email);
        etIdCard = (EditText) findViewById(R.id.et_idCard);
        btRegister = (Button) findViewById(R.id.bt_register);

        tvTitle.setText("注册");
        rbNan.setChecked(true);
    }

    @Override
    public void initEvent() {
        imBack.setOnClickListener(this);
        btRegister.setOnClickListener(this);
    }

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     * E/API: {"msg":"\r\n### Error updating database.  简而言之呢，就是我post的头像字段太大了，我看文档以为头像这东西吧，上传的类型是String，我以为直接转二进制上传，这波我在大气层
     *              Cause: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'avatar' at row 1\r\n###
     *              The error may exist in URL [jar:file:/D:/zhcsnew/server-v2/ljxl-admin.jar!/BOOT-INF/lib/ljxl-system-3.3.0.jar!/mapper/system/SysUserMapper.xml]\r\n###
     *              The error may involve com.ljxl.system.mapper.SysUserMapper.insertUser-Inline\r\n### The error occurred while setting parameters\r\n### SQL: insert into sys_user(user_name,nick_name,email,avatar,phonenumber,sex,password,create_by,            id_card,      balance,           create_time    )values(                  ?,       ?,       ?,       ?,       ?,       ?,       ?,             ?,            ?,      ?,           sysdate()    )\r\n###
     *              Cause: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'avatar' at row 1\n; Data truncation: Data too long for column 'avatar' at row 1;
     *              nested exception is com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'avatar' at row 1","code":500}
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    ContentResolver resolver = this.getContentResolver();
                    Bitmap bitmap = null;
                    try {
                        bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    Glide.with(this)
                            .load(bitmap)
                            .transform(new CircleCrop())
                            .into(avater);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG,80,byteArrayOutputStream);
                    byte[] bytesArrays = byteArrayOutputStream.toByteArray();
                    img = new String(Base64.encodeToString(bytesArrays,Base64.DEFAULT));

                }
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.im_back:
                destroyThis();
                break;
            case R.id.avater:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 1);
                break;
            case R.id.bt_register:
                if (TextUtils.hasEmpty(etName,etPwd,etPhone,etIdCard)){
                    showToast("有必填选项尚未填写");
                }else {
                    register();
                }
                break;
        }
    }

    private void register(){
        LoadedDialog dialog = new LoadedDialog(getThis());
        dialog.show();
        HashMap<String,Object> params = new HashMap<>();
        params.put("avatar",etAvater.getText().toString());
        params.put("userName",etName.getText().toString());
        params.put("nickName",etNick.getText().toString());
        params.put("password",etPwd.getText().toString());
        params.put("phonenumber",etPhone.getText().toString());
        params.put("sex",rbNan.isChecked()?"0":"1");
        params.put("email",etEmail.getText().toString());
        params.put("idCard",etIdCard.getText().toString());
        Api.config(ApiConfig.REGISTER,params).postRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                dialog.dismiss();
                if (res.contains("成功")){
                    destroyThis();
                    showToastSync("注册成功");
                }else {
                    showToastSync(res);
                }
            }

            @Override
            public void onFailure(Exception e) {
                dialog.dismiss();
            }
        },SPUtils.config(getThis(), Constant.SP_USER_FILE_NAME).getString(Constant.TOKEN));
    }
}